package com.wobangkj.common.api.pca;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wobangkj.common.model.pca.City;
import com.wobangkj.common.model.pca.Province;
import com.wobangkj.common.util.ip.IpUtil;
import com.wobangkj.tool.api.result.Result;
import com.wobangkj.tool.manager.cache.CacheManager;
import com.wobangkj.tool.manager.cache.impl.RedisManager;
import com.wobangkj.tool.model.CacheModel;
import com.wobangkj.common.model.pca.CityPinYin;
import com.wobangkj.common.util.pinyin.PinyinUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.Collator;
import java.util.*;

/**
 * 省市县
 *
 * @author lu
 */

@Controller
@RequestMapping(value = "/pca")
@Slf4j
public class PcaController {

	// 城市列表
	private final String pcaList = "pca.list";

	// 缓存
	private CacheManager cacheManager;

	@Autowired
	public void setRedis(RedisConnectionFactory redisConnectionFactory) {
		this.cacheManager = new RedisManager(redisConnectionFactory);
	}

	@GetMapping("/list")
	@ResponseBody
	public Object upload(@RequestParam(required = false) Map<String, Object> params) {

		CacheModel cacheModel = cacheManager.get(pcaList);

		if (cacheModel == null) {
			//log.info("[ykb项目路径]"+System.getProperty("user.dir"));
			File   file    = new File(System.getProperty("user.dir") + "/common-service/static/pca/pca-code.json");
			String content = null;
			try {
				content = FileUtils.readFileToString(file, "utf-8");
			} catch (IOException e) {
				log.error("[省市县文件读取异常]" + e.getMessage());
			}
			JSONArray json = JSON.parseArray(content);
			log.info("[省市县json解析]" + json);
			// add cache
			// one month
			cacheManager.set(pcaList, new CacheModel(60L * 24 * 30, json));
			return Result.GetMapDataSuccess(json);
		}
		return Result.GetMapDataSuccess(cacheModel.getData());
	}

	/**
	 * 获得所有城市列表
	 * json 解析到指定对象
	 *
	 * @param params
	 * @return
	 */
	@GetMapping("/city")
	@ResponseBody
	public Object city(@RequestParam(required = false) Map<String, Object> params) {

		String content = null;
		try {
			File file = new File(System.getProperty("user.dir") + "/common-service/static/pca/pca-code.json");
			content = FileUtils.readFileToString(file, "utf-8");
		} catch (IOException e) {
			log.error("[省市县文件读取异常]" + e.getMessage());
		}

		// 省市县对象
		List<Province> list = JSON.parseArray(content, Province.class);
		// 城市列表
		List<City> cities = new ArrayList<>();
		for (Province province : list) {
			for (City city : province.getChildren()) {
				// 直辖市处理
				// 更新为上级直辖市城市名
				if (city.getName().equals("市辖区")) {
					city.setName(province.getName());
				}
				// 移除下级区县
				city.setChildren(null);
			}
			// add all
			cities.addAll(province.getChildren());
		}

		// 城市字母排序
		Comparator rule = Collator.getInstance(Locale.CHINESE);
		Collections.sort(cities, (city, t1) -> rule.compare(city.getName(), t1.getName()));

		// 返回数据格式
		List<CityPinYin> cityPinYins = new ArrayList<>();
		// 城市首字母
		String     cityAZ     = PinyinUtil.getFirstUp(cities.get(0).getName());
		CityPinYin cityPinYin = new CityPinYin(cityAZ, cityAZ, null);
		// 某个拼音的所有城市
		List<City> cityList = new ArrayList<>();

		for (City city : cities) {
			String cityAZComp = PinyinUtil.getFirstUp(city.getName());

			// 首字母相同
			if (cityAZ.equals(cityAZComp)) {
				//cityPinYin.setItems(cities.);
				cityList.add(city);
				continue;
			}
			// 本次字母合并数据
			cityPinYin.setItems(cityList);
			cityPinYins.add(cityPinYin);
			// 下一个首字母
			cityAZ = cityAZComp;
			cityPinYin = new CityPinYin(cityAZ, cityAZ, null);
			// reflush
			cityList = new ArrayList<>();
		}
		// 最后一次合并
		cityPinYin.setItems(cityList);
		cityPinYins.add(cityPinYin);

		return Result.GetMapDataSuccess(cityPinYins);
	}

	/**
	 * 获取Ip地址
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/ip")
	@ResponseBody
	private Object getIpAdrress(HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>();
		map.put("ip", IpUtil.getIpAdrress(request));
		return Result.GetMapDataSuccess(map);
	}

	@GetMapping("/cityByIp")
	@ResponseBody
	private Object cityByIp(HttpServletRequest request) {

		String ip = IpUtil.getIpAdrress(request);

		// 腾讯 ip定位
		// 次数：企业开发者和个人开发者初始额度均为：日调用量10,000次，并发限制5次/秒
		// 次数不够, 多搞几个key, 负载均衡一下
		RestTemplate restTemplate = new RestTemplate();
		String       url          = "https://apis.map.qq.com/ws/location/v1/ip?ip=" + ip + "&key=3DBBZ-GXRCF-EJKJ7-JHOGR-FYAZV-Y6F42";
		HttpHeaders  headers      = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

		//HttpEntity<ModelMsg>           request  = new HttpEntity<>(data, headers);
		ResponseEntity<Object> response = restTemplate.getForEntity(url, Object.class);
		return Result.GetMapDataSuccess(response.getBody());
	}

}
